package ru.yermak.bookkeeping;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.ApplicationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdesktop.swingx.JXTaskPane;
import org.jdesktop.swingx.JXTaskPaneContainer;
import org.jdesktop.swingx.JXLoginPane;
import org.jdesktop.swingx.auth.LoginService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;

import ru.yermak.bookkeeping.common.UserDao;
import ru.yermak.bookkeeping.common.BookkeeperState;
import ru.yermak.bookkeeping.common.BookkeepingLoginService;
import ru.yermak.bookkeeping.model.User;

public class Bookkeeper {

    private final static Log log = LogFactory.getLog(Bookkeeper.class);

    private final static CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);

    public static void main(String[] args) {
        log.info("Starting bookkeeping...");
        final MyLoginService service = new MyLoginService();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final JXLoginPane panel = new JXLoginPane(service);
                final JFrame frame = JXLoginPane.showLoginFrame(panel);
                frame.setVisible(true);
            }
        }).start();


        String[] contextPaths = new String[]{"applicationContext.xml"};
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(contextPaths);
        service.setContext(context);
        COUNT_DOWN_LATCH.countDown();
    }

    private static class MyLoginService extends LoginService {
        private ApplicationContext context;

        public boolean authenticate(String name, char[] password,
                                    String server) throws Exception {
            COUNT_DOWN_LATCH.await();
            BookkeepingLoginService service = (BookkeepingLoginService) context.getBean("bookkeepingLoginService");
            boolean result = service.authenticate(name, new String(password));
            if (result) {
                JFrame frame = (JFrame) context.getBean("mainFrame");
                frame.setSize(new Dimension(700, 500));
                frame.setVisible(true);
            }
            return result;
        }


        public void setContext(ApplicationContext context) {
            this.context = context;
        }
    }
}
